﻿import re

import logging
from datetime import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
from google.appengine.api import mail

from views_common import *
import models

import PyRSS2Gen
import smth

# ##########################################################################################################################
# /
def echo(request):
    logging.info("url:"+request.POST.get('url', ""))
    logging.info("referrer:"+request.POST.get('referrer', ""))
    logging.info("title:"+request.POST.get('title', ""))
    logging.info("timestamp:"+request.POST.get('timestamp', ""))
    logging.info("html:"+ request.POST.get('html', ""))
    return HttpResponse('success!')

    
# ##########################################################################################################################
# /
def admin(request):
    user = getUser()
    if user.email() == 'ldmiao@gmail.com':
        command = request.GET.get("c", None)
        if command == 'cleanoldposts':
            models.cleanOldPosts(400)
            
        logging.info(user.email())
        
        return HttpResponse('success!')
        
    else:
        return HttpResponseRedirect('/')
    
# ##########################################################################################################################
# /
def index(request):
    user = getUser()
    
    logging.info(user.email())
    
    #config = models.Configuration.all().filter('user=', user).get()
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", user).get()
    
    if config is None:
        config = models.Configuration(user=user,showTitle=True,showHead=True,showPost=True,showRef=True,showSignature=True,showAttachment=True,showThreadNewPage=True,showThreadOriginUrl=True,threads_count=0,boards_count=0,posts_count=0)
        config.put()
        logging.info('new config added')
    
    login_text, login_url = getLoginAndUrl(request)
    
    top10_threads = smth.getTop10ArticlesList()
    
    top10_html = ''
    idx = 1;
    for thread in top10_threads:
        top10_html = top10_html + ('%02d' % idx) + " - <a href='/t/?bn=" + thread[2] + "&tid=" + thread[3] + "' style='color: red;'>" + thread[0] + "</a> <a href='/b/" + thread[2] + "/'>" + thread[2] + "</a> <br/>"
        idx = idx + 1
        


    
    payload = {'title': 'iPSmth - Smth for iPhone', 'contents': 'iPSmth - Smth for iPhone', 'login_text':login_text, 'login_url':login_url, 'config': config, 'top10_html': top10_html, }
    return render('board_index.html', payload)

# ##########################################################################################################################
# /b/
def board(request, board_name, page_num):
    #logging.info(page_num)
    
    threads, page_num_real = smth.getThreadList(board_name, page_num)
    
    
    html = '<h1><a href="/b/'+board_name+'/">'+board_name+'</a> <a href="/bp/'+board_name+'/">普通模式</a></h1>'
    
    pre_page = '上一页'
    next_page = '下一页'
    
    if page_num_real==page_num:
        next_page = '<a href="/b/'+board_name+'/?pn='+str(int(page_num_real)+1)+'">下一页</a>'
        
    if page_num_real>1:
        pre_page = '<a href="/b/'+board_name+'/?pn='+str(int(page_num_real)-1)+'">上一页</a>'
    
    html = html + '<a href="/b/'+board_name+'/?pn=1">|&lt;&lt;</a>  '
    html = html + pre_page
    html = html + '【第'+ page_num_real + '页】'
    html = html + next_page
    html = html + '  <a href="/b/'+board_name+'/">&gt;&gt;|</a><hr>'
    
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
    
    idx = len(threads);
    for thread in threads:
        #(thread_id, title, word_count, thread_url)
        html = html + '<a name="'+thread[0]+'">'+('%02d' % idx)+'</a>-<a href="/t/?bn='+board_name+'&tid='+thread[0]+'&tpn='+page_num_real+'">'+thread[1]+'('+thread[2]+')</a> ';
        if config.showThreadNewPage:
            html = html + '<a href="/t/?bn='+board_name+'&tid='+thread[0]+'" target="_blank">新窗口</a> '
        if config.showThreadOriginUrl:
            html = html + '<a href="http://www.newsmth.net/bbstcon.php?board='+board_name+'&gid='+thread[0]+'" target="_blank">原文</a>'
        html = html + '<br/>'
        idx = idx - 1
    
    
    html = html + '<hr><a href="/b/='+board_name+'/?pn=1">|&lt;&lt;</a>  '
    html = html + pre_page
    html = html + '【第'+ page_num_real + '页】'
    html = html + next_page
    html = html + '  <a href="/b/'+board_name+'/">&gt;&gt;|</a>'
    
    
    payload = {'title': board_name+' @ NewSmth', 'contents': html, }
    return render('board_threads.html', payload)

# ##########################################################################################################################
# /bn/
def bn(request):
    board_name = request.GET.get("bn", None)
    board_name_post = request.POST.get("bn", 'NewExpress')
    if board_name is None:
        board_name = board_name_post
    
    page_num = request.GET.get("pn", None)
    return board(request, board_name, page_num)

def b(request, board_name):
    page_num = request.GET.get("pn", None)
    if page_num == 0:
        page_num = None
    return board(request, board_name, page_num)
    
# ##########################################################################################################################
# /t/
def t(request):
    board_name = request.GET.get("bn", None)
    thread_id = request.GET.get("tid", None)
    page_num = request.GET.get("pn", None)
    thread_page_num = request.GET.get("tpn", "0")
    
    logging.info(page_num)
    
    thread_title, posts, page_num, page_count = smth.getThreadPostList(board_name, thread_id, page_num)
    
    
    
    if page_num==None:
        html = '此帖已被删除'
        payload = {'title': board_name+'@NewSmth', 'contents': html, }
        return render('board_threads.html', payload)
    else:
        if thread_title and thread_title.startswith('同主题阅读：'):
            thread_title = thread_title[thread_title.find('：')+3:]
            
        pre_page = '上一页'
        next_page = '下一页'
        
        if int(page_num) < int(page_count):
            next_page = '<a href="/t/?bn='+board_name+'&tid='+thread_id+'&tpn='+thread_page_num+'&pn='+str(int(page_num)+1)+'">下一页</a>'
        if int(page_num) > 1:
            pre_page = '<a href="/t/?bn='+board_name+'&tid='+thread_id+'&tpn='+thread_page_num+'&pn='+str(int(page_num)-1)+'">上一页</a>'
        
        config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
        
        html = ''
        
        #html = html + '<h1><a href="/b/'+board_name+'/">'+board_name+' @ NewSmth</a></h1>'
        if config and config.showTitle:
            html = html + '<h2>'+thread_title+'</h2>'
        
        thread_list_url = ''
        if thread_page_num:
            thread_list_url = '[<a href="/b/'+board_name+'/?pn='+thread_page_num+'#'+thread_id+'">主题列表</a>] '
        else:
            thread_list_url = '[<a href="/b/'+board_name+'/#'+thread_id+'">主题列表</a>] '
        html = html + thread_list_url
        
        html = html + '[' + pre_page + ' | '
        html = html + next_page + '] ['+page_num+'/'+page_count+'] ' 
        html = html +'<hr>'
        
        onloadscript = ''
        for post in reversed(posts):
            #(board_id, post_id, post_user)
            board_id = post[0]
            post_id = post[1]
            #html = html + '<a href="/p/?bid='+post[0]+'&pid='+post[1]+'">'+post[2]+'</a>'
            html = html + '<div id="'+post[1]+'">'
            
            post_db = db.GqlQuery("SELECT * FROM Post WHERE board_id=:1 and post_id=:2", int(board_id), int(post_id)).get()
            if post_db:
                
                html = html + post_db.toHTML(config).encode('utf-8', 'ignore')
            else:
                html = html + '<a href="/p/?bid='+board_id+'&pid='+post_id+'"><img src="/media/images/ajax-loader.gif"/></a>'
                onloadscript = onloadscript + 'getPostContent('+post[0]+','+post[1]+');\n'
            html = html + '</div><hr>'
            
        html = html + thread_list_url
        
        html = html + '[' + pre_page + ' | '
        html = html + next_page + '] ['+page_num+'/'+page_count+'] '
        
        #html = html + '<h1><a href="/b/'+board_name+'/">'+board_name+' @ NewSmth</a>'

        payload = {'title': thread_title+'@'+board_name+'@NewSmth', 'contents': html, 'onloadscript': onloadscript, }
        return render('board_threads.html', payload)
    
# ##########################################################################################################################
# /p/
def p(request):
    board_id = request.GET.get("bid", None)
    post_id = request.GET.get("pid", None)

    post = db.GqlQuery("SELECT * FROM Post WHERE board_id=:1 and post_id=:2", int(board_id), int(post_id)).get()
    if post is None:
        head, content_text, ref, attachment_html, signature = smth.getPostContent(board_id, post_id)
        
        post = models.Post(board_id=int(board_id), post_id=int(post_id), head=unicode(head, 'utf-8'), ref=unicode(ref, 'utf-8'), attachment=unicode(attachment_html, 'utf-8'), signature=unicode(signature, 'utf-8'), content=unicode(content_text, 'utf-8'))
        try:
            post.put()
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
            models.cleanOldPosts()
            mail.send_mail(sender="ipsmth@googleappengine.com",
              to="Demiao Lin <ldmiao@gmail.com>",
              subject="It seems that ipsmth had a OverQuotaError",
              body='''
Dear Demiao:

Your http://ipsmth.appspot.com just had a OverQuotaError:
--------------------------------
'''
+ message +
'''
--------------------------------

Please check it if you have time.

From: ipsmth@googleappengine.com
''')

    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
    
    return HttpResponse(post.toHTML(config))

# ##########################################################################################################################
# /bp/
def board_post(request, board_name, page_num):
    
    posts, board_id, page_num_real = smth.getPostList(board_name, page_num)
    
    
    html = '<h1><a href="/bp/'+board_name+'/">'+board_name+'</a> <a href="/b/'+board_name+'/">同主题</a></h1>'
    
    pre_page = '上一页'
    next_page = '下一页'
    
    if page_num_real==page_num:
        next_page = '<a href="/bp/'+board_name+'/?pn='+str(int(page_num_real)+1)+'">下一页</a>'
        
    if page_num_real>1:
        pre_page = '<a href="/bp/'+board_name+'/?pn='+str(int(page_num_real)-1)+'">上一页</a>'
    
    html = html + '<a href="/bp/'+board_name+'/?pn=1">|&lt;&lt;</a>  '
    html = html + pre_page
    html = html + '【第'+ page_num_real + '页】'
    html = html + next_page
    html = html + '  <a href="/bp/'+board_name+'/">&gt;&gt;|</a>'
    
    html = html + '<br/><span class="post" onclick="toggleAllPosts('+board_id+')">显示全部帖子内容</span><hr>'
    
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
    
    onloadscript = ''
    idx = 1;
    for post in posts:
        #(post_id, thread_id, user, tag, title, word_count, thread_url)
        html = html + '<a name="n'+post[0]+'">'+('%02d' % idx)+'</a>-<a href="#n'+post[0]+'" onclick="togglePost('+board_id+','+post[0]+');">'+post[4]+'('+post[5]+')<span class="type_attach">'+post[3]+'</span></a> ';
        html = html + '<a href="/t/?bn='+board_name+'&tid='+post[1]+'">同主题</a> '
        if config.showThreadNewPage:
            html = html + '<a href="/p/?bid='+board_id+'&pid='+post[0]+'" target="_blank">新窗口</a> '
        if config.showThreadOriginUrl:
            #http://www.newsmth.net/bbscon.php?bid=719&id=260710
            html = html + '<a href="http://www.newsmth.net/bbscon.php?bid='+board_id+'&id='+post[0]+'" target="_blank">原文</a>'
        #html = html + '<div class="p_div" id="'+post[0]+'" style="display:none;" onclick="togglePost('+board_id+','+post[0]+');"></div>'
        html = html + '<div class="p_div" id="'+post[0]+'" style="display:none;"></div>'
        #onloadscript +=  'getPostContent('+board_id+','+post[0]+');\n'
        html = html + '<br/>'
        idx = idx + 1
    
    
    html = html + '<hr><a href="/b/='+board_name+'/?pn=1">|&lt;&lt;</a>  '
    html = html + pre_page
    html = html + '【第'+ page_num_real + '页】'
    html = html + next_page
    html = html + '  <a href="/b/'+board_name+'/">&gt;&gt;|</a>'
    
    
    payload = {'title': board_name+' @ NewSmth', 'contents': html, 'onloadscript': onloadscript, }
    return render('board_posts.html', payload)
    
    
# ##########################################################################################################################
# /bp/
def bp1(request):
    board_name = request.GET.get("bn", None)
    board_name_post = request.POST.get("bn", 'NewExpress')
    if board_name is None:
        board_name = board_name_post
    
    page_num = request.GET.get("pn", None)
    return board_post(request, board_name, page_num)

def bp2(request, board_name):
    page_num = request.GET.get("pn", None)
    if page_num == 0:
        page_num = None
    return board_post(request, board_name, page_num)
# ##########################################################################################################################
# /c/
def c(request):
    showTitle = request.POST.get("showTitle", "False")
    showHead = request.POST.get("showHead", "False")
    showPost = request.POST.get("showPost", "False")
    showRef = request.POST.get("showRef", "False")
    showAttachment = request.POST.get("showAttachment", "False")
    showSignature = request.POST.get("showSignature", "False")
    
    showThreadNewPage = request.POST.get("showThreadNewPage", "False")
    showThreadOriginUrl = request.POST.get("showThreadOriginUrl", "False")
    
    if showTitle == 'True':
        showTitle = True
    else:
        showTitle = False
        
    if showHead == 'True':
        showHead = True
    else:
        showHead = False
        
    if showPost == 'True':
        showPost = True
    else:
        showPost = False
        
    if showRef == 'True':
        showRef = True
    else:
        showRef = False
        
    if showSignature == 'True':
        showSignature = True
    else:
        showSignature = False
    
    if showAttachment == 'True':
        showAttachment = True
    else:
        showAttachment = False
    
    if showThreadNewPage == 'True':
        showThreadNewPage = True
    else:
        showThreadNewPage = False
        
    if showThreadOriginUrl == 'True':
        showThreadOriginUrl = True
    else:
        showThreadOriginUrl = False
    
    
    user = getUser()
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", user).get()
    if config:
        config.showTitle = showTitle
        config.showHead = showHead
        config.showPost = showPost
        #logging.info('showPost:'+str(showPost))
        config.showRef = showRef
        config.showSignature = showSignature
        config.showAttachment = showAttachment
        config.showThreadNewPage = showThreadNewPage
        config.showThreadOriginUrl = showThreadOriginUrl
        config.put()
    
    return HttpResponseRedirect('/')
    